package main

import (
	"context"
	"fmt"
	"google.golang.org/grpc"
	"google.golang.org/grpc/status"
	"grpc-6/helper"
	"grpc-6/pb/services"
	"log"
)

func main() {
	//连接服务端
	//为避免缺少证书 no transport security set (use grpc.WithInsecure() explicitly or set credentials)
	/*conn, err := grpc.Dial(":8081", grpc.WithInsecure())
	if err != nil {
		log.Fatalf("连接GRPC服务端失败 %v\n", err)
	}

	defer conn.Close()
	prodClient := services.NewDownloadServiceClient(conn)

	download(prodClient, &services.DownloadRequest{
		FilePath: "C:\\Users\\ginzeng\\Desktop\\tmp\\dev.txt",
	})*/

	Download(":8081")

}

func download(client services.DownloadServiceClient, r *services.DownloadRequest) error {
	stream, err := client.Download(context.Background(), r)
	if err != nil {
		return err
	}
	for {
		resp, err := stream.Recv()
		status := status.Convert(err)

		if status.Code() == helper.EOF {
			fmt.Println("文件正常结束...")
			break
		}
		if err != nil {
			return err
		}
		fmt.Println("返回值:", resp)
	}

	return nil
}

func Download(host string) error {
	var (
		conn       *grpc.ClientConn
		err        error
		grpcClient services.DownloadServiceClient
	)
	conn, err = grpc.Dial(host, grpc.WithInsecure())
	if err != nil {
		log.Fatalf("grpc.Dial err: %v", err)
		return err
	}
	defer conn.Close()

	grpcClient = services.NewDownloadServiceClient(conn)

	return download(grpcClient, &services.DownloadRequest{FilePath: string("D:\\tmp\\note.txt")})
}
